<template>
  <el-drawer
    v-model="visible"
    :with-header="false"
    size="40%"
    class="detail-drawer"
    @close="onClose"
  >
    <div class="drawer-header">
      <div>
        <h2 class="drawer-title">{{ node?.label }}</h2>
        <p class="drawer-description">{{ node?.description }}</p>
      </div>
      <el-icon color="#b5b5b5" size="24" @click="visible = false"><Close /></el-icon>
    </div>

    <div class="drawer-body">
      <div v-if="node?.keyFeatures?.length" class="section-title">关键特征</div>
      <div v-if="node?.keyFeatures?.length" class="features-list">
        <div class="feature-item" v-for="(feature, index) in node?.keyFeatures" :key="index">
          {{ feature }}
        </div>
        <el-empty v-if="!node?.keyFeatures?.length" :image-size="150" description="暂无数据" />
      </div>

      <div class="tabs-container">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="学习单元" name="unit">
            <template #label>
              <span class="flex items-center gap-col-2px">
                <el-icon><Document /></el-icon>
                学习单元 ({{ unitTotal }})
              </span>
            </template>
            <div class="tab-content">
              <div
                v-infinite-scroll="handleUnitReachBottom"
                class="learning-unit-list"
                v-loading="unitLoading"
                :infinite-scroll-disabled="
                  unitLoadmoreState === 'finished' || unitLoadmoreState === 'error'
                "
                :infinite-scroll-immediate="false"
              >
                <template v-for="unit in unitList" :key="unit.id">
                  <FileListView :file-list="unit.url" useSlot disabledDownload alwaysShow>
                    <div class="learning-unit">
                      <div class="flex-1">
                        <div class="unit-title">{{ unit.title }}</div>
                        <div class="unit-preview">{{ unit.content || '' }}</div>
                      </div>
                      <div class="view-button flex items-center gap-col-5px">
                        <el-icon @click.stop="handleDelete(unit.id)"><Delete /></el-icon>
                        <el-icon><View /></el-icon>
                      </div>
                    </div>
                  </FileListView>
                </template>

                <div v-if="unitLoadmoreState === 'loading'" class="text-center p-4 text-gray-500">
                  加载中...
                </div>
              </div>
              <el-empty
                v-if="!unitList?.length && !unitLoading"
                :image-size="150"
                description="暂无数据"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="学习资源" name="resource">
            <template #label>
              <span class="flex items-center gap-col-2px">
                <el-icon><Film /></el-icon>
                学习资源 ({{ resourceTotal }})
              </span>
            </template>
            <div class="tab-content">
              <div
                v-infinite-scroll="handleResourceReachBottom"
                class="learning-resource-list"
                v-loading="resourceLoading"
                :infinite-scroll-disabled="
                  resourceLoadmoreState === 'finished' || resourceLoadmoreState === 'error'
                "
                :infinite-scroll-immediate="false"
              >
                <template v-for="resource in resourceList" :key="resource.id">
                  <FileListView :file-list="resource.url" useSlot disabledDownload alwaysShow>
                    <div class="learning-resource">
                      <div class="resource-icon">
                        <el-icon :size="20">
                          <Film />
                        </el-icon>
                      </div>
                      <div class="resource-info">
                        <div class="resource-title">{{ resource.title }}</div>
                        <div class="resource-type">{{ resource.content }}</div>
                      </div>
                      <div class="view-button flex items-center gap-col-5px">
                        <el-icon @click.stop="handleDelete(resource.id)"><Delete /></el-icon>
                        <el-icon><View /></el-icon>
                      </div>
                    </div>
                  </FileListView>
                </template>

                <div
                  v-if="resourceLoadmoreState === 'loading'"
                  class="text-center p-4 text-gray-500"
                >
                  加载中...
                </div>
              </div>
              <el-empty
                v-if="!resourceList?.length && !resourceLoading"
                :image-size="150"
                description="暂无数据"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="drawer-footer absolute bottom-20px left-0 right-0 w-100% flex justify-center">
      <el-button type="primary" @click="openForm('create')"> 添加资源 </el-button>
    </div>
    <!-- <el-empty v-else :image-size="200" description="暂无数据" /> -->
    <!-- 表单弹窗：添加/修改 -->
    <KnowledgeNodeResourceForm ref="nodeResourceFormRef" @success="refresh" />
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
  Document,
  Film,
  View,
  Files,
  VideoCamera,
  Picture,
  Close,
  Delete
} from '@element-plus/icons-vue'
import { KnowledgeNodeResourceApi } from '@/api/school/knowledge/nodeResource'
import { usePageList } from '@/hooks/web/usePageList'
import KnowledgeNodeResourceForm from '@/views/school/knowledge/nodeResource/KnowledgeNodeResourceForm.vue'

const props = defineProps({
  modelValue: Boolean,
  node: Object
})
const emit = defineEmits(['update:modelValue', 'open-unit', 'open-resource'])

const { t } = useI18n() // 国际化
const message = useMessage()

const visible = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

// const resourceMap = {
//   learningUnits: {
//     icon: Document,
//     name: '学习单元'
//   },
//   learningResources: {
//     icon: Film,
//     name: '学习资源'
//   },
//   file: {
//     icon: Files,
//     name: '文档'
//   },
//   video: {
//     icon: VideoCamera,
//     name: '视频'
//   },
//   image: {
//     icon: Picture,
//     name: '图片'
//   }
// }

const activeTab = ref('unit')
const nodeResourceFormRef = ref()
// 学习单元相关
const {
  list: unitList,
  total: unitTotal,
  loading: unitLoading,
  loadmoreState: unitLoadmoreState,
  queryParams: unitQueryParams,
  getList: getUnitList,
  handleReachBottom: handleUnitReachBottom
} = usePageList({
  toast: message,
  queryFn: KnowledgeNodeResourceApi.getKnowledgeNodeResourcePage,
  query: { resourceType: 'learningUnits' }
})

// 学习资源相关
const {
  list: resourceList,
  total: resourceTotal,
  loading: resourceLoading,
  loadmoreState: resourceLoadmoreState,
  queryParams: resourceQueryParams,
  getList: getResourceList,
  handleReachBottom: handleResourceReachBottom
} = usePageList({
  toast: message,
  queryFn: KnowledgeNodeResourceApi.getKnowledgeNodeResourcePage,
  query: { resourceType: 'learningResources' }
})

const openForm = (type: string, id?: number) => {
  nodeResourceFormRef.value.open(type, id, unitQueryParams.nodeId)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await KnowledgeNodeResourceApi.deleteKnowledgeNodeResource(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await refresh()
  } catch {}
}
const refresh = async () => {
  // 根据当前标签页加载对应数据
  if (activeTab.value === 'unit') {
    await getUnitList(true)
  } else {
    await getResourceList(true)
  }
}

// 监听节点变化，获取学习单元和资源
watch(
  () => props.node,
  async (newNode) => {
    // 重置数据
    unitList.value = []
    resourceList.value = []
    unitTotal.value = 0
    resourceTotal.value = 0

    if (newNode && newNode.id) {
      // 设置查询参数
      unitQueryParams.nodeId = newNode.id
      resourceQueryParams.nodeId = newNode.id
      await getUnitList(true)
      await getResourceList(true)
      // refresh()
    }
  },
  { immediate: true }
)

// 标签页切换处理
const handleTabChange = (tabName) => {
  if (props.node && props.node.id) {
    if (tabName === 'unit' && unitList.value.length === 0) {
      getUnitList(true)
    } else if (tabName === 'resource' && resourceList.value.length === 0) {
      getResourceList(true)
    }
  }
}

const onClose = () => {
  activeTab.value = 'unit'
}
</script>

<style lang="scss" scoped>
.detail-drawer {
  --el-drawer-padding-primary: 0;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  padding: 0 0 16px;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-title {
  margin-bottom: 8px;
  font-size: 22px;
  font-weight: 700;
  color: #1d3557;
}

.drawer-description {
  font-size: 14px;
  line-height: 1.6;
  color: #5a7f9c;
}

.drawer-body {
  height: calc(100% - 90px);
  // padding: 24px;
  overflow-y: auto;
}

.section-title {
  position: relative;
  padding-left: 12px;
  margin-top: 16px;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #1d3557;
}

.section-title::before {
  position: absolute;
  top: 5px;
  bottom: 5px;
  left: 0;
  width: 4px;
  background-color: var(--el-color-primary);
  border-radius: 2px;
  content: '';
}

.features-list {
  margin-bottom: 24px;
}

.feature-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  font-size: 14px;
  color: #1d3557;
}

.feature-item::before {
  margin-right: 8px;
  font-size: 16px;
  color: var(--el-color-primary);
  content: '•';
}

.tabs-container {
  margin-top: 20px;
}

.tab-content {
  margin-top: 16px;
}

.learning-unit-list,
.learning-resource-list {
  max-height: 400px;
  overflow-y: auto;
}

.learning-unit {
  display: flex;
  padding: 16px;
  margin-bottom: 12px;
  cursor: pointer;
  background-color: #f7f9fc;
  border-left: 3px solid var(--el-color-primary);
  border-radius: 10px;
  transition: all 0.3s;
}

.learning-resource:hover,
.learning-unit:hover {
  background-color: #edf7ff;
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgb(0 0 0 / 8%);
}

.unit-title {
  margin-bottom: 6px;
  font-size: 15px;
  font-weight: 600;
  color: #1d3557;
}

.unit-preview {
  display: -webkit-box;
  overflow: hidden;
  font-size: 13px;
  line-height: 1.5;
  color: #5a7f9c;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.learning-resource {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 10px;
  cursor: pointer;
  background-color: #f7f9fc;
  border-left: 3px solid var(--el-color-primary);
  border-radius: 10px;
  transition: all 0.3s;
}

.resource-icon {
  display: flex;
  width: 40px;
  height: 40px;
  margin-right: 12px;
  color: var(--el-color-primary);
  background: color-mix(in oklch, var(--el-color-primary), transparent 90%);
  border-radius: 8px;
  align-items: center;
  justify-content: center;
}

.resource-info {
  flex: 1;
}

.resource-title {
  margin-bottom: 4px;
  font-weight: 500;
  color: #1d3557;
}

.resource-type {
  font-size: 12px;
  color: #5a7f9c;
}

.view-button {
  color: var(--el-color-primary);
}
</style>
